<!--
    group: 发票管理
    name: 开票列表
    item: 批量核验---成功列表展示弹层
-->
<template>
  <a-modal
     wrapClassName="SingleDataVerification-con"
     :width="getWidth(dataType)"
     :title="title_"
     :visible="visible_"
     @cancel="handleCancel"
     :footer="null"
   >
   <!-- <a-alert message="当前开票数据已与其他开票请求合并核验，您可以：" type="warning" show-icon  /> -->
   <a-card title="发送成功！请提醒法人尽快完成核验！" style="width: 100%;margin: 5px 0;" :headStyle="{padding:'3px 10px','font-size':'14px',display:'flex','font-weight':'600'}">
     <a-table :columns="columns" :data-source="dataSource" bordered :pagination="false" :scroll="{y:400}">
       <!-- <template slot="name" slot-scope="text">
         <divBox :dataArr="text"></divBox>
       </template>
       <template slot="money" slot-scope="text">
         <divBox :dataArr="text" direction="right"></divBox>
       </template> -->
       <template slot="signUrl" slot-scope="text,record">
          <div class="code">
            <img class="img" :src="codeList[text]" alt="二维码图片">
            <a-button v-if="dataType=='InvitationVerification'" type="primary" style="margin: 0 20px;" @click.prevent="sendQRCode(record)" :size="'small'"> 下载二维码 </a-button>
          </div>
       </template>
       <template slot="signSMS" slot-scope="text,record">
          {{text.label}} <br/> <a :href="text.url">{{text.url}}</a><br/>
          <a-button v-if="dataType=='InvitationVerification'" type="primary" style="margin: 0 20px;" @click.prevent="InvitationVerification(record)" :size="'small'"> 发送核验短信 </a-button>
       </template>
       <template slot="footer" slot-scope="currentPageData" >
         <div :style="['display: flex;  align-items: center; padding-right: 0px;',dataType=='SVI'?'justify-content: center;':'justify-content: flex-end;'].join(' ')">
           <a-button v-if="dataType=='SVI' || dataType=='InvitationVerification'" type="primary" style="margin: 0 20px;" @click.prevent="handleCancel"> 关闭 </a-button>
           <a-button v-if="dataType=='IV'" type="primary" style="margin: 0 20px;" @click.prevent="InvitationVerification"> 发送核验短信 </a-button>
           <a-button v-if="dataType=='IV'" type="primary" style="margin: 0 20px;" @click.prevent="sendQRCode"> 下载二维码 </a-button>
         </div>
       </template>
     </a-table>
   </a-card>

   </a-modal>
</template>

<script>
import QRious from 'qrious'
import UUID from '@/utils/uuid'
import * as Util from '@/utils/util'
import {
  getInvoiceSignUrl, getTaxInvoiceCheckSendSms,getInvoiceBaseUrl,
  getInvoiceReturnSignUrl,getTaxReturnTicketBatchCheck,revokedBatchSMSByCatalog
} from '@api/invoiceAdminister'

const getColumns = (dataType='IV')=>{
  const tempArr = {
    // 单数据
    'IV':[
        {
          title: '购买方名称',
          align:'center',
          width:'300px',
          dataIndex: 'entName',
          //  scopedSlots: { customRender: 'name' },
        },
        {
          title: '开票金额',
          align:'center',
          width:'150px',
          className: 'column-money',
          dataIndex: 'amount',
          //  scopedSlots: { customRender: 'money' },
        },
        {
          title: '已发送核验短信',
          align:'center',
          width:'300px',
          dataIndex: 'signSMS',
          scopedSlots: { customRender: 'signSMS' },
        },
        {
          title: '核验二维码',
          align:'center',
          width:'150px',
          dataIndex: 'signUrl',
          scopedSlots: { customRender: 'signUrl' },
        },
    ],
    // 批量数据
    'SVI':[
        {
          title: '开票企业',
          align:'center',
          // width:'300px',
          dataIndex: 'entName',
          //  scopedSlots: { customRender: 'name' },
        },
        {
          title: '法人',
          align:'center',
          // width:'150px',
          // className: 'column-money',
          dataIndex: 'legalName',
          //  scopedSlots: { customRender: 'money' },
        },
        {
          title: '法人实名手机号',
          align:'center',
          // width:'150px',
          dataIndex: 'legalPhone',
        },
        {
          title: '已发送核验短信',
          align:'center',
          // width:'300px',
          dataIndex: 'signSMS',
          scopedSlots: { customRender: 'signSMS' },
        },
        {
          title: '核验二维码',
          align:'center',
          // width:'150px',
          dataIndex: 'signUrl',
           scopedSlots: { customRender: 'signUrl' },
        },
    ],
    // 撤销开票申请
    'InvitationVerification':[
        {
          title: '开票企业',
          align:'center',
          width:'300px',
          dataIndex: 'entName',
          //  scopedSlots: { customRender: 'name' },
        },
        {
          title: '法人',
          align:'center',
          width:'150px',
          // className: 'column-money',
          dataIndex: 'legalName',
          //  scopedSlots: { customRender: 'money' },
        },
        {
          title: '法人实名手机号',
          align:'center',
          width:'150px',
          dataIndex: 'legalPhone',
        },
        {
          title: '已发送核验短信',
          align:'center',
          width:'300px',
          dataIndex: 'signSMS',
          scopedSlots: { customRender: 'signSMS' },
        },
        {
          title: '核验二维码',
          align:'center',
          width:'150px',
          dataIndex: 'signUrl',
           scopedSlots: { customRender: 'signUrl' },
        },
    ],
  }

  return tempArr[dataType]
}


export default {
 // import引入的组件需要注入到对象中才能使用
 name: 'SingleDataVerification',
 components: {},
 props: {
  rowData: { type: [Object,Array], required: true},
  show:{type:Boolean,default:false},
  event:{type:Function},
  // 数据类型
  dataType:{type:String,default:'IV'}
 },
 data() {
   // 这里存放数据
   return {
    showCodeTitle:false,
     visible_:false,
     title_:'邀请验证',
     columns:[],
     dataSource:[],
     spinning:false,
     codeList:{}
   };
 },
 // 监听属性 类似于data概念
 computed: {},
 // 监控data中的数据变化
 watch: {
  rowData: {
     handler(val) {
      if(!this.isType.isNullOrUnDef(val)){
        this.dataSource = this.convData(val,this.dataType)
        // this.dataSource = val
      }
     },
     deep: true,
     immediate: true
   },
   dataType: {
     handler(val) {
      if(!this.isType.isNullOrUnDef(val)){
        this.columns = getColumns(val)
      }
     },
     deep: true,
     immediate: true
   },
   show: {
     handler(val) {
       if(!this.isType.isNullOrUnDef(val) && this.isType.isBoolean(val)){
         this.visible_ = val
       }
     },
     deep: true,
     immediate: true
   },
 },
 // 生命周期 - 创建完成（可以访问当前this实例）
 created() {},
 // 生命周期 - 挂载完成（可以访问DOM元素）
 mounted() {

 },
 // 方法集合
 methods: {
  getWidth(dataType){
    const w = {
      'IV':1000,
      'SVI':1200,
      'InvitationVerification':1200,
    }
    return w[dataType]
  },
  convData(data, dataType){
    const tempArr = []
    if(this.isType.isArray(data)){
      data.forEach(async item=>{
        const {signUrl,signSMS,amount} = item
        await this.getInvoiceUrl(signUrl,dataType)
        const tempAmount = Util.conversionElement(amount)+' 元'
        const signSMS_ = signSMS.replace(signUrl,'')
        // const temp = this.getBaseUrl(signUrl) //await this.getInvoiceUrl(signUrl)
        const temp = signUrl
        tempArr.push({...item,signUrl:temp,amount:tempAmount,signSMS:{label:signSMS_,url:signUrl}})
        // console.log(tempArr,temp,item);
      })
    }
    return tempArr
  },
  getBaseUrl(url){
      var qr = new QRious({
        // background: 'green',
        // backgroundAlpha: 0.8,
        // foreground: 'blue',
        // foregroundAlpha: 0.8,
        level: 'H',
        // padding: 5,
        // size: 120,
        value: url
      });
      return qr.toDataURL()
  },
    //获取图片Base
  async getInvoiceUrl(url,dataType){
      let params = {};
      params.url = url;
      params.key = '';
      if(dataType == 'SVI'){
        params.key = '业务核验';
      }
      const res = await getInvoiceBaseUrl(params)
      this.codeList[url] = res.value
      this.spinning = false;
      let code = ''
      if(res.success==true){
        code = res.value;
      }
      return code;
      // .then(res => {
      //   if (res.status == 0) {
      //     this.codeUrl = res.value;
      //     this.spinning = false;
      //   }else{
      //     this.$message.warning(res.message);
      //   }
      // })
    },
   handleCancel(){
     this.visible_ = false
     this.event&& this.event('SDVClose',this.visible_)
   },
   /**
    * 单独发送核验邀请
    */
   InvitationVerification(rowData){
     // 需要获取到  提示用户该条开票申请已绑定其他数据，列表中当前数据标红展示：
      //  this.event&& this.event('SDVSMS',this.rowData)
    this.resendEvent(rowData || this.rowData[0])
   },
   resendEvent(rowData){
    console.log('====>',rowData);
    if(this.dataType=='InvitationVerification'){
      let params = {catalogName:rowData.catalogName};
      revokedBatchSMSByCatalog(params).then(res => {
        if (res.success) {
          this.$message.success('发送成功');
          this.event&& this.event('IVRefresh',this.rowData)
        }else{
          this.$message.warning(res.message);
        }
      })
    }else{
      let params = {data:{ids:[rowData.invoiceId]}};
      getTaxInvoiceCheckSendSms(params).then(res => {
        if (res.success) {
          this.$message.success('发送成功');
        }else{
          this.$message.warning(res.message);
        }
      })
    }
  },
   /**
    * 拷贝二维码
    */
   sendQRCode(record){
     // 需要获取到  提示用户该条开票申请已绑定其他数据，列表中当前数据标红展示：
    //  this.event&& this.event('SDVQRCode',this.rowData)
    this.upDown(record || this.dataSource[0])
   },
    //复制二维码
    upDown(record){
      const {signUrl} =record
      console.log('复制二维码==>',record)
      if (signUrl){
        const imgUrl = signUrl;
        // 如果浏览器支持msSaveOrOpenBlob方法（也就是使用IE浏览器的时候），那么调用该方法去下载图片
        if (window.navigator.msSaveOrOpenBlob) {
          var bstr = atob(imgUrl.split(',')[1]);
          var n = bstr.length;
          var u8arr = new Uint8Array(n);
          while (n--) {
            u8arr[n] = bstr.charCodeAt(n);
          }
          var blob = new Blob([u8arr]);
          window.navigator.msSaveOrOpenBlob(blob, 'code' + '.' + 'png');
        } else {
          // 这里就按照chrome等新版浏览器来处理
          const a = document.createElement('a');
          a.href = imgUrl;
          a.setAttribute('download', 'code');
          a.click();
        }

        // this.$message.success('复制成功');
        this.codeShow = true;
      }
    },

 },
 }
</script>
<style lang='less' >
.SingleDataVerification-con{
  z-index: 1010;
 .ant-modal{
   .ant-modal-content{
     .ant-modal-header{
       .ant-modal-title{
         text-align:left;
       }
     }
   }
 }
 .ant-table-tbody > tr > td{
  //  padding:0;
 }
 .div-box-c{
   width: 100%;
   display: flex;
   justify-content:center;
   align-items: center;
   flex-direction: column;
   .div-box-item{
     width: 100%;
     height: 50px;
     display: flex;
     justify-content:center;
     align-items: center;
     border-bottom: 1px solid #e8e8e8;
     padding: 5px 8px;
     &.t-c{
       justify-content:center;
     }
     &.t-l{
       justify-content:flex-start;
     }
     &.t-r{
       justify-content:flex-end;
     }
     &.red{
       color: #fa0505;
       font-weight: bold;
     }
   }
   .div-box-item:last-child{
     border-bottom: 0px solid #e8e8e8;
   }
 }
}
</style>
